from flask import Flask, request, render_template
import json
import base64
from urllib.parse import urlencode
import requests
app = Flask(__name__)
def logs(req, res = None):
    with open("logs.log", "a") as f:
        print(req.form, req.host_url, req.remote_addr, file=f, sep="|")

@app.route("/", methods=["get"])
def index():
    logs(request)
    return render_template("index.html")


@app.route("/view", methods=["get"])
def view():
    logs(request)
    return render_template("view.html")

@app.route("/music", methods=["get"])
def music():
    api_url = "https://v1.alapi.cn/api/music/search"
    name = request.args.get("name")
    params = {"keyword": name}
    logs(request, params)
    rep = requests.post(api_url, params=params)
    music_data = json.loads(rep.text)["data"]["songs"]
    return {"music_result": music_data}

@app.route("/number", methods=["get"])
def airsearch():
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/numbers"
    urls = request.args.get("url")
    logs(request)
    rep = requests.get(urls).content
    img = base64.b64encode(rep)
    params = {"image": img}
    data = urlencode(params)
    access_token = '[24.e40005f39856f813fe92fc6d2ccabc3e.2592000.1612503834.282335-23492537]'
    post_params = {"access_token": access_token}
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    rep = requests.post(url, headers=headers, data=data, params=post_params)
    print(rep.text)
    datas = json.loads(rep.text)["words_result"]
    result = ""
    for i in datas:
        result += i["words"]
    return {"air": result}

@app.route("/bmisearch", methods=["get"])
def textdata():
    url = "http://zhouxunwang.cn/data/?id=143"
    sex = request.args.get("sex")
    height = request.args.get("height")
    weight = request.args.get("weight")
    params = {
        "key": "XeiXqIcyS9r+h5OP8Iw1TmjCPATgsJeZ/pxz6f4",
        "sex": sex,
        "height": height,
        "weight": weight
    }
    rep = requests.get(url, params=params)
    datas = json.loads(rep.text)
    result = datas["result"]
    return {"result": result}

@app.route("/viewlog", methods=["GET"])
def viewlog():
    with open("logs.log", "r") as f:
        contents = []
        for data in f:
            splits = data.split("|")
            contents.append({"Formdata" : splits[0], "Host_url": splits[1], "Remote_addr": splits[2]})
    return {"content": contents}

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)

